package com.study.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.dto.Result;
import com.study.entity.Shop;
import com.study.mapper.ShopMapper;
import com.study.service.IShopService;
import com.study.utils.CacheUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.study.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public Result queryById(Long id) {
        //缓存穿透代码块
        //Shop shop = queryShopThrough(id);
        //缓存穿透工具类实现
        Shop shop = cacheUtil.queryShopThrough(CACHE_SHOP_KEY, id, Shop.class, id2 -> getById(id2), 2L, TimeUnit.MINUTES);

        //缓存击穿互斥锁代码块
        //Shop shop = queryShopMutex(id);

        //缓存击穿逻辑过期代码块
       // Shop shop = queryWithlogicalExpire(id);

        //缓存击穿逻辑过期工具类实现
/*
        Shop shop = cacheUtil.queryWithlogicalExpire(CACHE_SHOP_KEY, id, Shop.class, id2 -> getById(id2), 2L, TimeUnit.MINUTES);
*/

        if (shop == null) {
            return Result.fail("没有查询到店铺信息！");
        }
        //返回店铺信息到客户端
        return Result.ok(shop);

    }

    /* private static final ExecutorService CACHE_EXECUTOR = Executors.newFixedThreadPool(10);

   private Shop queryWithlogicalExpire(Long id) {
        //根据id从Redis获取店铺信息
        String cacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //如果Redis中没有数据直接返回空信息
        if (StrUtil.isBlank(cacheShop)) {
            return null;
        }

        RedisData redisData = JSONUtil.toBean(cacheShop, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //如果没有过期则直接返回数据
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        //如果过去了进行数据重建
        String lockKey = LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        if(lock){
            CACHE_EXECUTOR.submit(() -> {
                try {
                    this.saveShopToRedis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }

        //返回店铺信息到客户端
        return shop;
    }*/


    /*private Shop queryShopThrough(Long id) {
        //根据id从Redis获取店铺信息
        String cacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //如果有直接返回信息
        if (StrUtil.isNotBlank(cacheShop)) {
            return JSONUtil.toBean(cacheShop, Shop.class);
        }
        //如果是空对象则直接返回报错信息，目的是为了缓存穿透
        if (cacheShop != null) {
            return null;
        }

        //如果没有则查询数据库
        Shop shop = query().getBaseMapper().selectById(id);

        //如果数据库没有店铺信息则返回错误信息
        if (ObjectUtil.isEmpty(shop)) {
            //Redis中存入空数据，防止数据穿透
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //如果数据库有店铺信息则保存到Redis中
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //返回店铺信息到客户端
        return shop;
    }*/

    /*private Shop queryShopMutex(Long id) {
        System.out.println("进入方法");
        //根据id从Redis获取店铺信息
        String cacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //如果有直接返回信息
        if (StrUtil.isNotBlank(cacheShop)) {
            return JSONUtil.toBean(cacheShop, Shop.class);
        }
        //如果是空对象则直接返回报错信息，目的是为了缓存穿透
        if (cacheShop != null) {
            return null;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            //获取锁，如果获取到了代表有线程在执行，等待再重试
            boolean tryLock = tryLock(lockKey);
            if (!tryLock) {
                Thread.sleep(50);
                return queryShopMutex(id);
            }
            //如果没有则查询数据库
            shop = query().getBaseMapper().selectById(id);
            //Thread.sleep(200);
            //如果数据库没有店铺信息则返回错误信息
            if (ObjectUtil.isEmpty(shop)) {
                //Redis中存入空数据，防止数据穿透
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            //如果数据库有店铺信息则保存到Redis中
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);


        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        //返回店铺信息到客户端
        return shop;
    }*/

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    //手动将热点信息放入Redis中
    /*public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        *//*Thread.sleep(200);*//*
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }*/
}
